<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
    center
  >
    <el-form
      :model="form"
      ref="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
      :inline="false"
      size="normal"
    >
      <el-form-item label="头像" prop="avatar">
        <!--
          action：上传地址
          on-success：成功之后调用的方法，它里面做两家事情，一是实现预览，二是给 form.avatar 赋值
          before-upload：上传之前，它里面做两家事情，一是限制文件的类型、大小，二是给后台需要的image属性赋值
          data：携带额外参数
          imageUrl：图片预览
          -->
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :data="uploadObj"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="图形码" prop="code">
            <el-input v-model="form.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <img
            style="width:100%;height:40px;"
            :src="registerCaptchaUrl"
            @click="changeRegisterCaptchaUrl"
            alt=""
          />
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="18">
          <el-form-item label="验证码" prop="rcode">
            <el-input v-model="form.rcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button @click="getRcode">获取用户验证码</el-button>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'register',
  data () {
    return {
      registerCaptchaUrl: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      dialogVisible: false,
      imageUrl: '', // 头像上传的地址
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads', // 头像上传地址
      uploadObj: {
        image: null // image 是后台要求的
      },
      form: {
        // 表单绑定的模型，它的属性来自接口
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        code: '', // 图形码
        rcode: ''
      },
      rules: {
        avatar: [
          { required: true, message: '头像不能为空', trigger: 'change' }
        ],
        username: [
          { required: true, message: '用户昵称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('邮箱不能为空'))
              }

              // 告诉eslint注释的下一行不用管它
              // eslint-disable-next-line
              const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
              if (!reg.test(value)) {
                return callback(new Error('邮箱不合法'))
              }

              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              // rule：规则对象，一般不用它
              // value：就是输入的值
              // callback：决定校验成功还是失败，如果失败 callback(new Error('错误提示'))，成功 callback()，无论成功还是失败都要调用
              if (!value) {
                return callback(new Error('手机号不能为空'))
              }

              const reg = /^1[3456789][0-9]{9}$/
              if (!reg.test(value)) {
                return callback(new Error('手机号不合法'))
              }

              // 一定要调用callback，否则登录按钮就不起效
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码长度必须在6-16位之间',
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '图形码不能为空', trigger: 'blur' },
          {
            min: 4,
            max: 4,
            message: '图形码长度必须是4位',
            trigger: 'blur'
          }
        ],
        rcode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          {
            min: 4,
            max: 4,
            message: '验证码长度必须是4位',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    dialogVisible (newValue) {
      if (!newValue) {
        // 清空表单的内容
        this.$refs.form.resetFields()

        // 手动清空图像预览
        this.imageUrl = ''
      }
    }
  },
  methods: {
    changeRegisterCaptchaUrl () {
      this.registerCaptchaUrl =
        process.env.VUE_APP_BASEURL +
        '/captcha?type=sendsms&t=' +
        (new Date() - 0)
    },
    handleAvatarSuccess (res, file) {
      // 实现图片预览
      this.imageUrl = URL.createObjectURL(file.raw)

      // console.log('---res---', res)
      if (res.code === 200) {
        // 上传成功
        this.form.avatar = res.data.file_path
      } else {
        // 上传失败
        this.$message.error(res.message)
      }
    },
    // 上传之前
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      // 给上传时候的额外参数赋值
      this.uploadObj.image = file

      // 返回值为 true 才发起上传请求
      return isImage && isLt2M
    },
    // 获取验证码
    async getRcode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })

      if (num === 2) {
        const res = await this.$axios.post('/sendsms', {
          phone: this.form.phone,
          code: this.form.code
        })

        if (res.code === 200) {
          this.form.rcode = `${res.data.captcha}`
        } else {
          // 提示
          this.$message.error(res.message)

          // 刷新
          this.changeRegisterCaptchaUrl()
        }
      }
    },
    submit () {
      // 全部校验
      this.$refs.form.validate(async valid => {
        if (!valid) return

        const res = await this.$axios.post('/register', this.form)
        if (res.code === 200) {
          // 提示
          this.$message.success('注册成功~')

          // 关闭对话框
          this.dialogVisible = false
        } else {
          // 提示
          this.$message.error(res.message)

          // 刷新验证码
          this.changeRegisterCaptchaUrl()
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep.avatar-uploader {
  text-align: center;
}
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
